﻿using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KQ.DCMMP.Common
{
    public static class InvokeExtensions
    {

        /// <summary>
        /// Safely invoke methods by catching non fatal exceptions and logging them
        /// </summary>
        public static void Invoke<TEvents>(this IEnumerable<TEvents> events,
            Action<TEvents> dispatch)
        {
            foreach (var sink in events)
            {
                try
                {
                    dispatch(sink);
                }
                catch (Exception ex)
                {
                    LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
                    writer.Write(string.Format(
                        "Message:{3}.StackTrace:{4}. {2} thrown from {0} by {1}",
                        typeof(TEvents).Name,
                        sink.GetType().FullName,
                        ex.GetType().Name,
                        ex.Message,
                        ex.StackTrace));
                }
            }
        }

        public static IEnumerable<TResult> Invoke<TEvents, TResult>(
            this IEnumerable<TEvents> events,
            Func<TEvents, TResult> dispatch)
        {
            foreach (var sink in events)
            {
                TResult result = default(TResult);
                try
                {
                    result = dispatch(sink);
                }
                catch (Exception ex)
                {
                    LogWriter writer = EnterpriseLibraryContainer.Current.GetInstance<LogWriter>();
                    writer.Write(string.Format(
                        "Message:{3}.StackTrace:{4}. {2} thrown from {0} by {1}",
                        typeof(TEvents).Name,
                        sink.GetType().FullName,
                        ex.GetType().Name,
                        ex.Message,
                        ex.StackTrace));
                }

                yield return result;
            }
        }
    }
}